package com.zcz.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zcz.config.FilterProperties;
import com.zcz.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * zuul网关过滤器
 * @author 王卫帅
 */
@Component
public class Filter extends ZuulFilter {

    @Autowired
    private FilterProperties filterProp;
    /**
     * 过滤器类型 pre route post error
     * @return
     */
    @Override
    public String filterType() {
        System.err.println("第一个pre");
        return "pre"; //四种类型定义
    }

    /**
     * 执行顺序，返回值越小，优先级越高
     * @return
     */
    @Override
    public int filterOrder() {
        System.err.println("第二个");
        //优先级，数字越大，优先级越低
        return 10;
    }

    /**
     * 是否执行run方法
     * @return
     */
    @Override
    public boolean shouldFilter() {
        System.err.println("第三个");
        //初始化context 上下文对象，servlet spring
        RequestContext context = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = context.getRequest();
        //获取请求路径
        String requestURI = request.getRequestURI();
        System.err.println(request.getRequestURI()+"*********");
        // 判断白名单
        //true 执行run方法 false不执行run方法
        return !isAllowPath(requestURI);
        //return true;
    }
    /**
     * 遍历配置文件里的白名单
     */
    private boolean isAllowPath(String requestURI) {
        // 定义一个标记
        boolean flag = false;
        // 遍历允许访问的路径
        for (String path : this.filterProp.getAllowPaths()) {
            // 然后判断是否是符合
            if(requestURI.startsWith(path)){
                flag = true;
                break;
            }
        }
        return flag;
    }
    /**
     * 编写过滤器的业务逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run(){
        System.err.println("进入run方法");
        //初始化context 上下文对象，servlet spring
        RequestContext context = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = context.getRequest();
        //获取请求路径
        System.err.println(request.getServletPath());
        System.err.println(request.getRequestURI());
        System.err.println("获取token"+request.getParameter("tokenid"));
        //获取请求头里的tokenid    待测试
        //String tokenid  = request.getHeader("auth");
        String tokenid  = request.getParameter("tokenid");
        if(StringUtils.isNotBlank(tokenid)){
            try {
                Claims claims = JwtUtil.parseJWT(tokenid);
                //Claims claims = JwtUtil.parseJWT(tokenid);
            } catch (Exception e) {
                //token 不正确 或者过期
                //拦截，不转发请求
                context.setSendZuulResponse(false);
                //相应状态码，401-身份未认证
                context.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
                JSONObject json = new JSONObject();
                json.put("msg","token不合法或者已经过期");
                //设置响应提示
                context.setResponseBody(json.toJSONString());
                //设置编码格式和参数的类型  json
                HttpServletResponse response = context.getResponse();
                response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                context.set("isSuccess",false);
                //throw new RuntimeException("token不存在");

            }
        }else {
             //拦截，不转发请求
            context.setSendZuulResponse(false);
            //相应状态码，401-身份未认证
            context.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            JSONObject json = new JSONObject();
            json.put("msg","token不存在");
            //设置响应提示
            context.setResponseBody(json.toJSONString());
            //设置编码格式和参数的类型  json
            HttpServletResponse response = context.getResponse();
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            context.set("isSuccess",false);

        }
        //返回值null，就代表该过滤器什么都不做
        return null;
    }
}
